# 极简修复脚本 - 创建一个干净的_process_loop函数
import os
import re
import datetime
import time
import queue
import logging

# 文件路径
original_file = r'd:\未知\yolo_apply\video_processing\video_processor.py'
final_backup = r'd:\未知\yolo_apply\video_processing\video_processor.py.final_backup'
temp_file = r'd:\未知\yolo_apply\video_processing\minimalist_fixed.py'

# 确保我们使用最终备份
if os.path.exists(final_backup):
    print(f"Using backup for minimalist fix: {final_backup}")
    
    # 读取文件内容
    with open(final_backup, 'r', encoding='utf-8', errors='replace') as f:
        content = f.read()
    
    # 找到_process_loop函数并替换为干净的版本
    function_pattern = r'def _process_loop\(self\):.*?\n(?![ \t])(?:def|class|$)'  # 简单的函数匹配模式
    
    # 创建一个干净的_process_loop函数版本
    clean_process_loop = '''def _process_loop(self):
        """处理视频帧的主循环"""
        # 初始化变量
        error_count = 0
        frame_count = 0
        try:
            logger.info(f"[{self.camera_id}] 处理线程已启动")
            
            while self.running:
                # 基本的循环结构
                if hasattr(self, 'stopped') and self.stopped:
                    break
                
                try:
                    # 处理队列中的帧
                    max_queue_size = self.config.get('max_queue_size', 50)
                    
                    # 获取帧并进行处理
                    if hasattr(self, 'frame_queue') and not self.frame_queue.empty():
                        # 从队列中获取帧
                        frame_data = self.frame_queue.get(timeout=1.0)
                        
                        if frame_data is None:
                            continue
                        
                        # 提取帧和时间戳
                        if isinstance(frame_data, tuple) and len(frame_data) >= 2:
                            frame = frame_data[0]
                            timestamp = frame_data[1]
                        else:
                            frame = frame_data
                            timestamp = datetime.datetime.now()
                        
                        frame_count += 1
                        
                        # 按照配置的间隔处理帧
                        frame_interval = self.config.get('frame_interval', 1)
                        if frame_count % frame_interval != 0:
                            continue
                        
                        # 目标检测
                        if hasattr(self, 'detection_engine') and self.detection_engine:
                            try:
                                # 执行目标检测
                                detection_results = self.detection_engine.detect(frame)
                                
                                # 处理检测结果
                                if detection_results:
                                    # 触发检测回调
                                    if hasattr(self, 'on_detection_callback') and self.on_detection_callback:
                                        try:
                                            self.on_detection_callback(self.camera_id, detection_results, timestamp)
                                        except Exception as cb_e:
                                            logger.error(f"检测回调执行失败: {str(cb_e)}")
                            except Exception as det_e:
                                logger.error(f"目标检测失败: {str(det_e)}")
                                
                        # 更新统计信息
                        if hasattr(self, 'stats') and isinstance(self.stats, dict):
                            self.stats['frames_processed'] += 1
                    else:
                        # 队列为空时短暂休眠
                        time.sleep(0.01)
                except queue.Empty:
                    # 队列为空异常，继续下一次循环
                    continue
                except Exception as e:
                    # 处理单帧处理过程中的错误
                    logger.error(f"处理单帧时出错: {str(e)}")
                    error_count += 1
                    
                    # 错误计数超过阈值时尝试恢复
                    if error_count >= 10:
                        logger.warning(f"连续错误次数过多，重置错误计数")
                        error_count = 0
                        
                        # 尝试自动恢复
                        if hasattr(self, '_attempt_recovery') and callable(self._attempt_recovery):
                            try:
                                self._attempt_recovery('_process_loop')
                            except Exception as rec_e:
                                logger.error(f"恢复过程出错: {str(rec_e)}")
                    
                    # 短暂休眠避免CPU占用过高
                    time.sleep(0.1)
                
        except Exception as e:
            # 错误处理
            logger.error(f"处理循环出错: {str(e)}")
            # 更新错误统计
            if hasattr(self, 'stats') and isinstance(self.stats, dict):
                self.stats['process_errors'] += 1
                self.stats['total_errors'] += 1
            # 错误率过高时触发警告和恢复
            error_count = 0
        finally:
            # 清理资源
            logger.info(f"[{self.camera_id}] 处理线程已停止")
            # 确保线程状态正确设置
            if hasattr(self, 'process_thread'):
                self.process_thread = None
            # 清空处理队列
            if hasattr(self, 'frame_queue'):
                while not self.frame_queue.empty():
                    try:
                        self.frame_queue.get_nowait()
                    except queue.Empty:
                        break'''
    
    # 替换函数
    new_content = re.sub(function_pattern, clean_process_loop + '\n\n', content, flags=re.DOTALL | re.MULTILINE)
    
    # 如果没有找到函数，我们就直接添加到文件末尾
    if new_content == content:
        print("Could not find _process_loop function pattern, appending clean version")
        new_content += '\n\n' + clean_process_loop
    
    # 写入修复后的文件
    with open(temp_file, 'w', encoding='utf-8') as f:
        f.write(new_content)
    
    print(f"Created minimalist fixed file: {temp_file}")
    
    # 替换原文件
    os.replace(temp_file, original_file)
    print(f"Replaced original file with minimalist fixed version")
    print("Now let's try to compile again...")
else:
    print(f"Error: Final backup file not found: {final_backup}")